<template>
  <div class="storage-config-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>存储配置</span>
          <el-button type="primary" @click="handleSave" :loading="saving">保存配置</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="150px"
        class="storage-form"
      >
        <el-form-item label="存储类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择存储类型"
            style="width: 100%"
            @change="handleTypeChange"
          >
            <el-option label="本地存储" value="local">
              <span style="float: left">本地存储</span>
              <span style="float: right; color: #8492a6; font-size: 13px">文件存储到服务器本地</span>
            </el-option>
            <el-option label="阿里云OSS" value="aliyun_oss">
              <span style="float: left">阿里云OSS</span>
              <span style="float: right; color: #8492a6; font-size: 13px">文件存储到阿里云对象存储</span>
            </el-option>
            <el-option label="腾讯云COS" value="tencent_cos">
              <span style="float: left">腾讯云COS</span>
              <span style="float: right; color: #8492a6; font-size: 13px">文件存储到腾讯云对象存储</span>
            </el-option>
            <el-option label="七牛云" value="qiniu">
              <span style="float: left">七牛云</span>
              <span style="float: right; color: #8492a6; font-size: 13px">文件存储到七牛云</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="配置名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入配置名称" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
          <div class="form-tip">禁用后，文件上传将无法使用此存储配置</div>
        </el-form-item>

        <!-- 本地存储配置 -->
        <template v-if="form.type === 'local'">
          <el-divider content-position="left">本地存储配置</el-divider>
          <el-form-item label="存储根目录" prop="config.root">
            <el-input v-model="form.config.root" placeholder="例如：uploads">
              <template #append>
                <el-button @click="form.config.root = 'uploads'">默认</el-button>
              </template>
            </el-input>
            <div class="form-tip">文件将存储到 storage/app/public/ 目录下</div>
          </el-form-item>
          <el-form-item label="访问URL" prop="config.url">
            <el-input v-model="form.config.url" placeholder="例如：/storage">
              <template #append>
                <el-button @click="form.config.url = '/storage'">默认</el-button>
              </template>
            </el-input>
            <div class="form-tip">文件访问的URL前缀</div>
          </el-form-item>
        </template>

        <!-- 阿里云OSS配置 -->
        <template v-if="form.type === 'aliyun_oss'">
          <el-divider content-position="left">阿里云OSS配置</el-divider>
          <el-form-item label="AccessKey ID" prop="config.access_key_id">
            <el-input
              v-model="form.config.access_key_id"
              placeholder="请输入AccessKey ID"
              show-password
            />
          </el-form-item>
          <el-form-item label="AccessKey Secret" prop="config.access_key_secret">
            <el-input
              v-model="form.config.access_key_secret"
              type="password"
              show-password
              placeholder="请输入AccessKey Secret"
            />
          </el-form-item>
          <el-form-item label="Bucket名称" prop="config.bucket">
            <el-input v-model="form.config.bucket" placeholder="请输入Bucket名称" />
          </el-form-item>
          <el-form-item label="Endpoint" prop="config.endpoint">
            <el-input v-model="form.config.endpoint" placeholder="例如：oss-cn-hangzhou.aliyuncs.com" />
            <div class="form-tip">OSS的Endpoint地址，不包含http://或https://</div>
          </el-form-item>
          <el-form-item label="自定义域名" prop="config.domain">
            <el-input v-model="form.config.domain" placeholder="可选：自定义域名" />
            <div class="form-tip">如果配置了自定义域名，文件将通过此域名访问</div>
          </el-form-item>
          <el-form-item label="使用CNAME" prop="config.is_cname">
            <el-switch v-model="form.config.is_cname" />
            <div class="form-tip">是否使用CNAME方式访问</div>
          </el-form-item>
        </template>

        <!-- 腾讯云COS配置 -->
        <template v-if="form.type === 'tencent_cos'">
          <el-divider content-position="left">腾讯云COS配置</el-divider>
          <el-form-item label="SecretId" prop="config.secret_id">
            <el-input
              v-model="form.config.secret_id"
              placeholder="请输入SecretId"
              show-password
            />
          </el-form-item>
          <el-form-item label="SecretKey" prop="config.secret_key">
            <el-input
              v-model="form.config.secret_key"
              type="password"
              show-password
              placeholder="请输入SecretKey"
            />
          </el-form-item>
          <el-form-item label="地域（Region）" prop="config.region">
            <el-input v-model="form.config.region" placeholder="例如：ap-guangzhou" />
            <div class="form-tip">COS存储桶所在地域</div>
          </el-form-item>
          <el-form-item label="Bucket名称" prop="config.bucket">
            <el-input v-model="form.config.bucket" placeholder="请输入Bucket名称" />
          </el-form-item>
          <el-form-item label="自定义域名" prop="config.domain">
            <el-input v-model="form.config.domain" placeholder="可选：自定义域名" />
            <div class="form-tip">如果配置了自定义域名，文件将通过此域名访问</div>
          </el-form-item>
        </template>

        <!-- 七牛云配置 -->
        <template v-if="form.type === 'qiniu'">
          <el-divider content-position="left">七牛云配置</el-divider>
          <el-form-item label="AccessKey" prop="config.access_key">
            <el-input
              v-model="form.config.access_key"
              placeholder="请输入AccessKey"
              show-password
            />
          </el-form-item>
          <el-form-item label="SecretKey" prop="config.secret_key">
            <el-input
              v-model="form.config.secret_key"
              type="password"
              show-password
              placeholder="请输入SecretKey"
            />
          </el-form-item>
          <el-form-item label="Bucket名称" prop="config.bucket">
            <el-input v-model="form.config.bucket" placeholder="请输入Bucket名称" />
          </el-form-item>
          <el-form-item label="访问域名" prop="config.domain">
            <el-input v-model="form.config.domain" placeholder="请输入访问域名" />
            <div class="form-tip">七牛云存储空间的访问域名，例如：https://your-domain.com</div>
          </el-form-item>
        </template>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSave" :loading="saving">保存配置</el-button>
          <el-button @click="handleTest" :loading="testing">测试连接</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const formRef = ref(null)
const saving = ref(false)
const testing = ref(false)

const form = reactive({
  id: null,
  type: 'local',
  name: '本地存储',
  status: 1,
  config: {
    root: 'uploads',
    url: '/storage',
    access_key_id: '',
    access_key_secret: '',
    secret_id: '',
    secret_key: '',
    access_key: '',
    bucket: '',
    endpoint: '',
    region: '',
    domain: '',
    is_cname: false,
  },
  remark: '',
})

const rules = {
  type: [
    { required: true, message: '请选择存储类型', trigger: 'change' },
  ],
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' },
  ],
}

// 初始化配置
const initConfig = () => {
  form.config = {
    root: 'uploads',
    url: '/storage',
    access_key_id: '',
    access_key_secret: '',
    secret_id: '',
    secret_key: '',
    access_key: '',
    bucket: '',
    endpoint: '',
    region: '',
    domain: '',
    is_cname: false,
  }
}

// 加载配置
const loadConfig = async () => {
  try {
    const res = await request.get('/storage-config')
    if (res.code === 200 && res.data) {
      Object.assign(form, {
        id: res.data.id,
        type: res.data.type || 'local',
        name: res.data.name || '本地存储',
        status: res.data.status !== undefined ? res.data.status : 1,
        config: res.data.config || {},
        remark: res.data.remark || '',
      })
      
      // 确保config对象有所有字段
      form.config = {
        root: form.config.root || 'uploads',
        url: form.config.url || '/storage',
        access_key_id: form.config.access_key_id || '',
        access_key_secret: form.config.access_key_secret || '',
        secret_id: form.config.secret_id || '',
        secret_key: form.config.secret_key || '',
        access_key: form.config.access_key || '',
        bucket: form.config.bucket || '',
        endpoint: form.config.endpoint || '',
        region: form.config.region || '',
        domain: form.config.domain || '',
        is_cname: form.config.is_cname || false,
      }
    }
  } catch (error) {
    console.error('加载配置失败:', error)
    ElMessage.error('加载配置失败')
  }
}

// 存储类型改变
const handleTypeChange = () => {
  // 根据类型设置默认名称
  const typeNames = {
    local: '本地存储',
    aliyun_oss: '阿里云OSS',
    tencent_cos: '腾讯云COS',
    qiniu: '七牛云',
  }
  form.name = typeNames[form.type] || '存储配置'
  
  // 重置配置（保留当前值，只初始化缺失的字段）
  const currentConfig = { ...form.config }
  initConfig()
  form.config = { ...form.config, ...currentConfig }
}

// 保存配置
const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    saving.value = true
    
    const res = await request.put('/storage-config', form)
    if (res.code === 200) {
      ElMessage.success('保存成功')
      await loadConfig() // 重新加载配置
    }
  } catch (error) {
    if (error.errors) {
      ElMessage.error('验证失败，请检查输入')
    } else {
      ElMessage.error(error.message || '保存失败')
    }
  } finally {
    saving.value = false
  }
}

// 测试连接
const handleTest = async () => {
  try {
    await formRef.value.validate()
    
    testing.value = true
    
    const res = await request.post('/storage-config/test', {
      type: form.type,
      config: form.config,
    })
    
    if (res.code === 200) {
      ElMessage.success('连接测试成功')
    } else {
      ElMessage.error(res.message || '连接测试失败')
    }
  } catch (error) {
    if (error.errors) {
      ElMessage.error('验证失败，请检查输入')
    } else {
      ElMessage.error(error.message || '连接测试失败')
    }
  } finally {
    testing.value = false
  }
}

// 重置
const handleReset = async () => {
  try {
    await ElMessageBox.confirm('确定要重置配置吗？重置后将恢复为默认配置', '提示', {
      type: 'warning',
    })
    
    initConfig()
    form.type = 'local'
    form.name = '本地存储'
    form.status = 1
    form.remark = ''
    
    ElMessage.success('已重置为默认配置')
  } catch (error) {
    // 用户取消
  }
}

onMounted(() => {
  loadConfig()
})
</script>

<style scoped lang="scss">
.storage-config-container {
  // padding 由 app-container 统一管理
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.storage-form {
  max-width: 800px;
  margin: 0 auto;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.5;
}

.el-divider {
  margin: 20px 0;
}
</style>
